/*
 * @Description: 路由守卫
 * @Author: James324
 * @Date: 2023-08-18 15:48:49
 * @LastEditors: James324
 * @LastEditTime: 2024-03-25 09:32:07
 */
import router from '../index';
import { constantRoute, NotFoundRoute, userAsyncRoutes } from '../routes';
import { setTransitionName } from '../helper';
import { getToken } from '@/utils';
import { Global, WhiteList } from '@/config';
import { GlobalStore } from '@/store';
import type { Route, RouteRecordRaw } from 'vue-router';
import nProgress from 'nprogress';
import 'nprogress/nprogress.css';

nProgress.configure({
    showSpinner: false
});

const setDocumentTitle = (title: string = Global.title) => {
    document.title = title;
};

// 检查是否存在于免登陆白名单
const inWhiteList = (toPath: string) => {
    const path = WhiteList.find(value => {
        const reg = new RegExp('^' + value);
        return reg.test(toPath);
    });
    return !!path;
};

let isGetAsyncRoutes = false; //这个是用于判断动态路由是否已经被获取

router.beforeEach(async (to, from, next) => {
    nProgress.start();

    const title = to.meta.title as string;
    const token = getToken();

    if (title) {
        setDocumentTitle(title);
    }

    // 检查to.path是否存在于免登陆白名单
    if (inWhiteList(to.path)) {
        if (to.path === '/login') {
            if (token) {
                next('/home');
            } else {
                isGetAsyncRoutes = false;
                next();
            }
            return;
        }
    }

    if (!token) {
        isGetAsyncRoutes = false;
        next({ path: '/login', query: { redirect: decodeURIComponent(from.path) } });
    } else {
        if (!isGetAsyncRoutes) {
            const globalStore = GlobalStore();

            const res: any = await globalStore.getUserInfo(); // 获取用户信息

            if (res) {
                const menuAsyncRoutes = [...userAsyncRoutes, ...NotFoundRoute];

                globalStore.setAllRoutes(constantRoute, menuAsyncRoutes);
                globalStore.setAsyncRoutes(userAsyncRoutes);

                menuAsyncRoutes.forEach((route: Route) => {
                    if (router.hasRoute(route.name!)) return; // 存在路由记录
                    if (route.level === 1 || !route.parent) {
                        router.addRoute(route as RouteRecordRaw);
                    } else {
                        router.addRoute(route.parent, route as RouteRecordRaw);
                    }
                });

                isGetAsyncRoutes = true;
            }
            next({ ...to, replace: true }); // 解决路由动态添加后刷新空白
        } else {
            next();
        }
    }
});

// 全局后置钩子
router.afterEach((to, from) => {
    nProgress.done(true);
    setTransitionName(to, from); // 设置路由动画
});

// 全局捕获页面异步错误
window.addEventListener('unhandledrejection', () => {
    nProgress.done(true);
});
